package com.example.ojsandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.example.ojsandbox.model.ExecuteCodeRequest;
import com.example.ojsandbox.model.ExecuteCodeResponse;
import com.example.ojsandbox.model.ExecuteMessage;
import com.example.ojsandbox.model.JudgeInfo;
import com.example.ojsandbox.utils.ProcessUtils;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;


public class JavaNativeCodeSandbox implements CodeSandbox {

    private static final long TIME_OUT=5000L;

    private static final List<String> blackList=Arrays.asList("Files","exec");

    private static final WordTree WORD_TREE;

    static {
        WORD_TREE =new WordTree();
        WORD_TREE.addWords(blackList);
    }
    public static void main(String[] args) {

        JavaNativeCodeSandbox javaNativeCodeSandbox = new JavaNativeCodeSandbox();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();

        executeCodeRequest.setInputList(Arrays.asList("1 2", "1 3"));
        //String code = ResourceUtil.readStr("testCode/simpleCompute/Main.java", StandardCharsets.UTF_8);
        String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");

        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        //校验代码中是否包含黑名单中的命令
        FoundWord foundWord = WORD_TREE.matchWord(code);
        if(foundWord!=null){
            System.out.println("包含禁止词：" + foundWord.getFoundWord());
            return null;
        }

        //1.把用户的代码转为文件，保存到本地的tmpCode目录下
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + "tmpCode";
        if (FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        File userCodeFile = FileUtil.writeString(code, userCodeParentPath + File.separator + "Main.java", StandardCharsets.UTF_8);

        //2.编译代码，得到class文件
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage=ProcessUtils.runProcessAndGetMessage(compileProcess,"编译");
            System.out.println(executeMessage);
        } catch (Exception e) {
           return getErrorResponse(e);
        }

        //3.执行代码
        List<ExecuteMessage> executeMessageList=new ArrayList<>();
        for(String inputArgs :inputList){
            String runCmd=String.format("java -Xmx256m -Dfile.encoding=utf-8 -cp %s Main %s",userCodeParentPath,inputArgs);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);
                //判断恶意代码执行超时的情况
                new Thread(()->{
                    try {
                        Thread.sleep(TIME_OUT);
                        //若代码超过5秒没有执行完成，则显示超时错误
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });

                ExecuteMessage executeMessage=ProcessUtils.runProcessAndGetMessage(runProcess,"运行");
                //ExecuteMessage executeMessage=ProcessUtils.runInteractProcessAndGetMessage(runProcess,inputArgs);
                System.out.println(executeMessage);
                executeMessageList.add(executeMessage);
            } catch (Exception e) {
                return getErrorResponse(e);
            }
        }

        //4.收集整理输出结果
        ExecuteCodeResponse executeCodeResponse=new ExecuteCodeResponse();
        List<String> outputList=new ArrayList<>();
        long MaxTime=0;
        for(ExecuteMessage executeMessage:executeMessageList){
            String errorMessage=executeMessage.getErrorMessage();
            if(StrUtil.isNotBlank(errorMessage)){
                executeCodeResponse.setMessage(errorMessage);
                //用户提交的代码执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            if(executeMessage.getTime()!=null){
                MaxTime=Math.max(MaxTime,executeMessage.getTime());
            }
        }

        if(outputList.size()==executeMessageList.size()){
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo=new JudgeInfo();
       // judgeInfo.setMemory();
        judgeInfo.setTime(MaxTime);

        executeCodeResponse.setJudgeInfo(judgeInfo);

        if(userCodeFile.getParentFile()!=null){
            boolean del=FileUtil.del(userCodeParentPath);
            System.out.println("删除"+(del? "成功":"失败"));
        }
         return executeCodeResponse;
    }
    /*
     封装一个错误处理类，获取错误响应
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e){
        ExecuteCodeResponse executeCodeResponse=new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        //表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }
}
